import * as THREE from "three"
import Stats from 'three/addons/libs/stats.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

let renderer, camera, scene, controls, stats
let target

let material

const WIDTH = 256
const HEIGHT = 256

let mirrorCamera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1500)

let time = 0

let plane, box, depthScene, orthCamera;

const clock = new THREE.Clock();

init();
animate();
createMirror()

function init() {
    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1500);
    camera.position.set(0, 10, 20);

    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x333333);

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);


    var axesHelper = new THREE.AxesHelper(5000);
    scene.add(axesHelper);

    stats = new Stats();
    document.body.appendChild(stats.dom);

    controls = new OrbitControls(camera, renderer.domElement);

    window.addEventListener("resize", onWindowResize, false);
}


function createRenderTarget() {
    target = new THREE.WebGLRenderTarget(WIDTH, HEIGHT);
    target.texture.format = THREE.RGBFormat;
    target.texture.minFilter = THREE.NearestFilter;
    target.texture.magFilter = THREE.NearestFilter;
    target.texture.generateMipmaps = false;

    mirrorCamera.position.copy(camera.position);

}

function createMirror() {

    const box = new THREE.BoxGeometry(1, 1, 1)
    const mesh = new THREE.Mesh(box)
    mesh.position.z += 2
    scene.add(mesh)

    const geometry = new THREE.PlaneGeometry(5, 5)
    material = new THREE.ShaderMaterial({

        uniforms: {
            map: {
                value: null
            }
        },

        vertexShader: `
            varying vec2 vUv;
            void main(){
                vUv = uv;
                gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
            }
        `,
        fragmentShader: `
            uniform sampler2D map;
            varying vec2 vUv;
            void main(){
                vec4 color = texture2D(map,vUv);
                gl_FragColor = color;
            }
        `
    })
    plane = new THREE.Mesh(geometry, material)
    scene.add(plane);

}


function onWindowResize() {
    windowHalfX = window.innerWidth / 2;
    windowHalfY = window.innerHeight / 2;

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);
}

//
function animate() {
    requestAnimationFrame(animate);

    render();
    stats.update();
}

function render() {
    time = clock.getElapsedTime() / 2;



    renderer.render(scene, camera);
}